#include "PlayerManager.h"

PlayerManager::PlayerManager()
{
	//ctor
}

PlayerManager::~PlayerManager()
{
	//dtor
}

Player* PlayerManager::GetPlayer(int _Playerid)
{
	if(m_PlayerMap.count(_Playerid) != 0)
	{
		return &m_PlayerMap[_Playerid];
	}

	Debug::Error(__func__, "() error. not found. id:", _Playerid);
	return nullptr;
}


Player* PlayerManager::GetPlayerByFd(int _fd)
{
	if(m_fdIDMap.count(_fd) != 0)
	{
		return GetPlayer(m_fdIDMap[_fd]);
	}

	Debug::Error(__func__, "() error. not found. fd:", _fd);
	return nullptr;
}

bool PlayerManager::UpdateFDID(int _fd, int _playerId)
{
	m_fdIDMap[_fd] = _playerId;
	return true;
}

// 根据UserId 返回PlayerId -1:代表内存中还没有该用户的玩家信息;
int PlayerManager::GetPlayerIdByUserId(int _userId, int _fd)
{
	m_userIdFdMap[_userId] = _fd;
	Debug::State(__func__, "() add fd. _userId:", _userId, ", _fd:", _fd);

	if(m_UserIdPlayerIdMap.count(_userId)>0)
		return m_UserIdPlayerIdMap[_userId];

	return -1;
}

int PlayerManager::GetUserFd(int _userId)
{
	if(m_userIdFdMap.count(_userId))
		return m_userIdFdMap[_userId];

	Debug::Error(__func__, "() error. not found fd. _userId:", _userId, ", mapCount:", m_userIdFdMap.size());
	for(auto iter: m_userIdFdMap)
	{
		Debug::Log("Key value: ", iter.first, "," ,iter.second);
	}

	return -1;
}

int PlayerManager::GetUserId(int _fd)
{
//	for(map<int,int>::iterator iter :)
	for(auto iter = m_userIdFdMap.begin(); iter != m_userIdFdMap.end(); iter++)
	{
		if(iter->second == _fd)
			return iter->first;
	}

	Debug::Error(__func__, "(). _fd:", _fd);
	return -1;
}

// 更新玩家数据
bool PlayerManager::UpdatePlayer(const Player& _Player)
{
	// 先查找本地是否有 没有就创建 有就更新
	int playerId = _Player.m_oid;
	Player* pPlayer = GetPlayer(playerId);
	if(pPlayer != nullptr)
	{
		pPlayer->m_roleId = _Player.m_roleId;
		pPlayer->m_silver = _Player.m_silver;
		pPlayer->m_diamond = _Player.m_diamond;

		return true;
	}

	// 插入内存中
	m_PlayerMap[playerId] = _Player;

	return true;
}

